﻿using System;
using Microsoft.SharePoint;

namespace Eneta.Portal.Common.Repository
{
    public class ModerationRepository : BaseRepository
    {
        public ModerationRepository(SPWeb web)
            : base(web)
        {
        }

        public SPListItem GetItemBy(int itemId, Guid listId, string webUrl)
        {
            SPListItem item = null;
            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                    using (var site = new SPSite(SiteId))
                    {
                        using (SPWeb currentWeb = site.OpenWeb(webUrl))
                        {
                            item = GetItemById(currentWeb, itemId, listId);
                        }
                    }                                            
            });
            SPSecurity.RunWithElevatedPrivileges(sec);

            return item;
        }

        private SPListItem GetItemById(SPWeb web, int id, Guid listId)
        {
            var list = web.Lists[listId];
            var item = list.GetItemById(id);
            return item;
        }

        public bool ApproveItem(int itemId, Guid listId, string webUrl, string comment)
        {
            bool approved = false;
            SPListItem item = GetItemBy(itemId, listId, webUrl);
            var sec = new SPSecurity.CodeToRunElevated(
                delegate
                {
                        approved = ModerateItem(item, SPModerationStatusType.Approved, comment);
                });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return approved;
        }

        public bool DeclineItem(int itemId, Guid listId, string webUrl, string comment)
        {
            bool denied = false;
            SPListItem item = GetItemBy(itemId, listId, webUrl);
            var sec = new SPSecurity.CodeToRunElevated(
                delegate
                {
                    denied = ModerateItem(item, SPModerationStatusType.Denied, comment);
                });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return denied;
        }

        private bool ModerateItem(SPListItem item, SPModerationStatusType moderationStatusType, string comment)
        {
            if (item == null)
            {
                Logger.LogInfo("Moderation item is null");
                return false;
            }
            if (!item.ParentList.EnableModeration)
            {
                Logger.LogInfo(item.ParentList.Title + "'s moderation is not enabled");
                return false;
            }
            item.ModerationInformation.Comment = comment;
            item.ModerationInformation.Status = moderationStatusType;
            item.Update();
            return true;
        }
    }
}
